package com.by.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.by.entity.Brand;
import com.by.result.Result;
import com.by.service.BrandService;
import com.by.vo.BrandVo;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/brand")
public class BrandController {


    @Autowired
    private BrandService brandService;


    /**
     * 品牌列表(分页查询)
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param name 品牌名称
     * @return 品牌列表
     */
    @GetMapping("/list")
    public Result<IPage<BrandVo>> list(@RequestParam(defaultValue = "1") int pageNum,
                                      @RequestParam(defaultValue = "10") int pageSize,
                                      @RequestParam(required = false) String name) {
        return Result.success(brandService.pageBrand(pageNum, pageSize,name));
    }

    /**
     * 品牌详情
     * @param brandId 品牌ID
     * @return 品牌详情
     */
    @GetMapping("/detail")
    public Result<Brand> detail(@RequestParam("brandId") Long brandId) {
        return Result.success(brandService.getById(brandId));
    }

    /**
     * 添加品牌
     * @param brandVo 品牌信息
     * @return 品牌ID
     */
    @PostMapping("/save")
    public Result<Long> save(@RequestBody BrandVo brandVo) {
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandVo, brand);
        brandService.saveOrUpdate(brand);
        return Result.success(brand.getBrandId());
    }

    /**
     * 删除品牌
     * @param brandId 品牌ID
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public Result<Boolean> delete(@RequestParam("brandId") Long brandId) {
        // 1. 判断品牌是否存在
        Brand brand = brandService.getById(brandId);
        if (brand == null) {
            return Result.error(400, "品牌不存在");
        }
        return Result.success(brandService.removeById(brandId));
    }

    /**
     * 更新品牌
     * @param brandVo 品牌信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody BrandVo brandVo) {
        // 1. 判断品牌是否存在
        Brand brand = brandService.getById(brandVo.getBrandId());
        if (brand == null) {
            return Result.error(400, "品牌不存在");
        }
        BeanUtils.copyProperties(brandVo, brand);
        return Result.success(brandService.saveOrUpdate(brand));
    }
}
